package com.bwie.filter;

import com.alibaba.nacos.api.utils.StringUtils;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * @Author: 鑫仔
 * @Date: 2025/7/18 19:09
 * @Description:
 **/
@Component
@Order(1)
public class MyFilter implements GlobalFilter {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("路径" + path);

        //设置白名单
        if (path.contains("userLogin") || path.contains("sendCode") || path.contains("userReg")) {
            System.out.println("白名单" + path);
            return chain.filter(exchange);
        }

        //校验token
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            System.out.println("token不存在" + path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        Integer userId = Jwts.parser().setSigningKey("bwie").parseClaimsJws(token).getBody().get("id", Integer.class);
        String tokenKey = "token-" + userId;
        String redisToken = redisTemplate.opsForValue().get(tokenKey);
        if (StringUtils.isEmpty(redisToken)) {
            System.out.println("token过期" + path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        if (!token.equals(redisToken)) {
            System.out.println("token不一致" + path);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //续期
        redisTemplate.expire(redisToken, 60, TimeUnit.MINUTES);

        //放行
        return chain.filter(exchange);
    }
}












